let express = require("express");
let router = express.Router();
let db = require("../db/index");

router.post('/add', function (req, res, next) {
  let {title, society_id, start_time, end_time, num_of_people, signin_require, activity_address, overview} = req.body;
  db.query(`INSERT INTO activity set ?`, {
    title,
    society_id,
    start_time,
    end_time,
    num_of_people,
    signin_require,
    activity_address,
    overview
  }, function (err) {
    if (!err) {
      res.send({
        code: 200,
        message: '发布活动成功'
      })
    } else {
      res.send({
        code: 20009,
        message: err.message
      })
    }
  })
})

router.post('/update', function (req, res) {
  let {title, start_time, end_time, num_of_people, activity_address, signin_require, id} = req.body;
  db.query(`UPDATE activity SET title = ?,start_time = ?,end_time = ?,num_of_people = ?,activity_address=?,signin_require=? WHERE id = ?`, [title, start_time, end_time, num_of_people, activity_address, signin_require, id], function (err) {
    if (err) {
      res.send({
        code: 20006,
        message: '更新失败'
      })
    } else {
      res.send({
        code: 200,
        message: '成功'
      })
    }
  })
})

router.post('/info', function (req, res) {
  let {society_id, pageNo, limit, onlyNotExpired, timestamp, needInforms} = req.body;
  let start = (pageNo - 1) * limit
  if (onlyNotExpired) {
    var sql = `SELECT * FROM activity WHERE society_id = '${society_id}' AND end_time > ${timestamp} ORDER BY id DESC LIMIT ${start},${limit}`
    var sql2 = `SELECT count(id) AS total FROM activity WHERE society_id = '${society_id}' AND end_time > ${timestamp}`
  } else {
    var sql = `SELECT * FROM activity WHERE society_id = '${society_id}' ORDER BY id DESC LIMIT ${start},${limit}`
    var sql2 = `SELECT count(id) AS total FROM activity WHERE society_id = '${society_id}'`
  }
  db.query(sql, function (err, rows) {
    if (!err) {
      db.query(sql2, async function (err2, rows2) {
        if (needInforms) {
          let activities = await Promise.all(
              rows.map(item => {
                return new Promise(resolve => {
                  db.query(`SELECT * FROM activity_inform WHERE activity_id = '${item.id}'`, function (err3, informs) {
                    db.query(`SELECT count(id) as total FROM activity_join WHERE activity_id = ${item.id}`, function (err4, n) {
                      item.informs = informs;
                      item.num_of_participants = n[0].total || 0;
                      resolve(item);
                    })
                  })
                })
              })
          )
          res.send({
            code: 200,
            message: '成功',
            data: {
              activities,
              total: rows2[0].total
            }
          })
        } else {
          res.send({
            code: 200,
            message: '成功',
            data: {
              activities: rows,
              total: rows2[0].total
            }
          })
        }
      })
    } else {
      res.send({
        code: 20012,
        message: err.message
      })
    }
  })
})

// 签到信息
router.post('/info/signin', function (req, res) {
  let {society_id, limit, pageNo} = req.body;
  let start = (pageNo - 1) * limit;
  db.query(`SELECT at.*,count(at.id) as join_num
            FROM activity at LEFT JOIN activity_join aj ON at.id=aj.activity_id 
            WHERE at.society_id = ${society_id} AND at.signin_require=1 
            GROUP BY at.id
            ORDER BY at.id DESC
            LIMIT ${start},${limit}`,
      async function (err, rows) {
        if (!err) {
          let activities = await Promise.all(
              rows.map(item => new Promise((resolve => {
                db.query(`SELECT id FROM activity_join WHERE activity_id=${item.id} AND signin = 1`, function (err2, arr) {
                  item.signin_num = arr.length;
                  resolve(item);
                })
              })))
          )
          db.query(`SELECT count(*) as total FROM activity WHERE society_id = ${society_id} AND signin_require=1`, function (err3, arr2) {
            res.send({
              code: 200,
              message: "ok",
              activities,
              total: arr2[0].total
            })
          })
        } else {
          res.send({
            code: 20087,
            message: "获取签到信息失败"
          })
        }
      })
})

router.get('/info/signin/detail', function (req, res) {
  let {activity_id} = req.query;
  db.query(`SELECT aj.*,a.name,a.stu_code FROM activity_join aj LEFT JOIN account a ON aj.user_id = a.id WHERE aj.activity_id = ${activity_id}`,
      function (err, rows) {
        if (!err) {
          res.send({
            code: 200,
            message: "ok",
            signinList:rows
          })
        } else {
          res.send({
            code: 20087,
            message: "获取签到信息失败"
          })
        }
      })
})

router.post('/info/history', function (req, res) {
  let {society_id, pageNo, limit, user_id} = req.body;
  let start = (pageNo - 1) * limit
  var sql = `SELECT * FROM activity WHERE society_id = '${society_id}' ORDER BY id DESC LIMIT ${start},${limit}`
  var sql2 = `SELECT count(id) AS total FROM activity WHERE society_id = '${society_id}'`

  db.query(sql, function (err, rows) {
    if (!err) {
      db.query(sql2, async function (err2, rows2) {
        db.query(`SELECT activity_id FROM activity_join WHERE user_id = ${user_id}`, function (err3, rows3) {
          let ids = rows3.map(item => item.activity_id);
          let activities = rows.map(item => {
            item.joined = ids.includes(item.id);
            return item
          })
          res.send({
            code: 200,
            message: '成功',
            data: {
              activities,
              total: rows2[0].total
            }
          })
        })
      })
    } else {
      res.send({
        code: 20012,
        message: err.message
      })
    }
  })
})

router.post('/info/processing', function (req, res) {
  let {timestamp, user_id} = req.body;
  let sql = `SELECT a.*,j.signin 
               FROM activity_join j LEFT JOIN activity a ON j.activity_id = a.id 
               WHERE j.user_id = ${user_id} AND a.start_time < ${timestamp} AND a.end_time > ${timestamp}`
  db.query(sql, async function (err, rows) {
    if (!err) {
      let activities = await Promise.all(
          rows.map(item => {
            return new Promise(resolve => {
              db.query(`SELECT * FROM activity_inform WHERE activity_id = '${item.id}'`, function (err3, informs) {
                db.query(`SELECT count(id) as total FROM activity_join WHERE activity_id = ${item.id}`, function (err4, n) {
                  item.informs = informs;
                  item.num_of_participants = n[0].total || 0;
                  resolve(item);
                })
              })
            })
          })
      )
      res.send({
        code: 200,
        message: '成功',
        activities
      })
    } else {
      res.send({
        code: 20012,
        message: err.message
      })
    }
  })
})

router.post('/del', function (req, res) {
  let {ids} = req.body;
  db.query(`DELETE FROM activity WHERE id in (${ids})`, function (err) {
    if (err) {
      res.send({
        code: 20003,
        message: err.message
      })
    } else {
      res.send({
        code: 200,
        message: '成功'
      })
    }
  })
})

// 签到
router.get('/signin', function (req, res) {
  const {activity_id, user_id, timestamp} = req.query;
  db.query(`UPDATE activity_join set ? WHERE activity_id=${activity_id} AND user_id = ${user_id}`, {
    signin: 1,
    signin_time: timestamp
  }, function (err) {
    if (err) {
      res.send({
        code: 20006,
        message: '更新失败'
      })
    } else {
      res.send({
        code: 200,
        message: '成功'
      })
    }
  });
})

// 活动报名
router.get('/join', function (req, res) {
  let {user_id, activity_id, creationTime} = req.query;
  db.query(`SELECT * FROM activity_join WHERE user_id = ${user_id} AND activity_id = ${activity_id}`, function (error, arr) {
    if (arr.length > 0) {
      res.send({
        code: 20098,
        message: '已经报过名了'
      })
    } else {
      db.query('INSERT INTO activity_join set ?', {user_id, activity_id, creationTime}, function (err) {
        if (!err) {
          res.send({
            code: 200,
            message: '成功'
          })
        } else {
          res.send({
            code: 20099,
            message: err.message
          })
        }
      })
    }
  })


})

router.post('/inform/add', function (req, res) {
  let {title, activityId, overview, creationTime, society_id} = req.body;
  db.query(`INSERT INTO activity_inform set ?`, {
    title,
    activity_id: activityId,
    overview,
    need_confirm: 0,
    creationTime,
    society_id
  }, function (err) {
    if (!err) {
      res.send({
        code: 200,
        message: '成功'
      })
    } else {
      res.send({
        code: 2022,
        message: err.message
      })
    }
  })
})

router.post('/inform/update', function (req, res) {
  let {id, title, overview, needConfirm} = req.body;
  db.query(`UPDATE activity_inform set title=?,overview=?,need_confirm=? WHERE id = '${id}'`, [title, overview, needConfirm], function (err) {
    if (err) {
      res.send({
        code: 20041,
        message: err.message
      })
    } else {
      res.send({
        code: 200,
        message: '成功'
      })
    }
  })
})

router.get('/informs/get', function (req, res) {
  let {activity_id} = req.query;
  let sql = `SELECT * FROM activity_inform WHERE activity_id = '${activity_id}' ORDER BY id DESC`
  db.query(sql, function (err, rows) {
    if (!err) {
      res.send({
        code: 200,
        message: '成功',
        data: {
          informs: rows,
        }
      })
    } else {
      res.send({
        code: 20012,
        message: err.message
      })
    }
  })
})

router.get('/inform/delete', function (req, res) {
  let {id} = req.query;
  db.query(`DELETE FROM activity_inform WHERE id = '${id}'`, function (err) {
    if (err) {
      res.send({
        code: 20031,
        message: '删除失败'
      })
    } else {
      res.send({
        code: 200,
        message: '成功',
      })
    }
  })
})


module.exports = router;